# -*- coding:utf-8 -*-

import time

from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware


def add_cors_middleware(app: FastAPI):
    """
    添加跨域中间件

    :param app: FastAPI对象
    :return:
    """
    # 前端页面url
    origins = [
        '*'
        # 'http://localhost:80',
        # 'http://127.0.0.1:80',
        # 'http://127.0.0.1:9099',
        # 'http://localhost',
        # 'http://localhost/',
    ]

    # 后台api允许跨域
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )


def handle_middleware(app: FastAPI):
    """
    全局中间件处理
    """
    # 加载跨域中间件
    add_cors_middleware(app)
    
    @app.middleware('http')
    async def add_process_time_header(request: Request, call_next)-> Response:
        start_time = time.time()
        response = await call_next(request)
        process_time = round((time.time() - start_time) * 1000, 2)
        response.headers["X-Process-Time"] = f'{str(process_time)}ms'
        return response
